import prompt from '../../utils/prompt.js';
import {
  checkRequire,
  checkMoblePhone,
  checkAuthCode,
  checkImgCode
} from '../../utils/validator.js';
import Api from '../../utils/api.js';

const app = getApp();

// pages/register/register.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

    /* 验证码相关 */
    imgCodeSrc: '/images/icon_home.png',
    isCountingDown: false,
    authCodeBtnText: '获取验证码',
    authTimer: null,

    uuid: '', // 图片验证码id
    mpOpenid: '', // 公众号openid
    tel: '', // 手机号
    authCode: '', // 验证码
    imgCode: '', // 图形验证码

    telPass: true,
    imgCodePass: true,
    authCodePass: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad (options) {
    await app.appLogin();
    this.setData({ mpOpenid: options.mpOpenid || '' });
    this.getImgCodeSrc();
  },

  /* --==================网络请求==================-- */
  // 获取图片验证码地址
  async getImgCodeSrc () {
    const res = await Api.getCodeImage({ time: Date.now() });
    if (res.header && res.header.uuid) {
      this.setData({ uuid: res.header.uuid });
    }
    if (res.data) {
      const base64Str = wx.arrayBufferToBase64(res.data);
      let url = `data:image/png;base64,${base64Str}`;
      this.setData({ imgCodeSrc: url });
    }
  },
  // 获取短信验证码
  async getAuthCode () {
    const res = await Api.getVerifyCode({
      uuid: this.data.uuid,
      userCaptcha: this.data.imgCode,
      userTel: this.data.tel,
      sessionKey: app.globalData.sessionKey || ''
    });
    if (res) {
      prompt.showToast('发送短信验证码成功');
      this.startCountdown();
    } else {
      this.closeCountdonw();
    }
  },
  // 注册
  async register () {
    const res = await Api.register({
      mpOpenid: this.data.mpOpenid,
      userSmsCode: this.data.authCode,
      userTel: this.data.tel,
      sessionKey: app.globalData.sessionKey
    });
    if (res) {
      prompt.showToast('注册成功', 'success');
      wx.reLaunch({
        url: '/pages/index/index'
      });
    }
  },

  /* --==================功能函数==================-- */
  // 开始倒计时
  startCountdown () {
    if (!this.data.isCountingDown) {
      let time = 60;
      this.setData({ authCodeBtnText: time-- + 's' });
      const timer = setInterval(() => {
        if (time === 0) {
          this.closeCountdonw();
        } else {
          this.setData({ authCodeBtnText: time-- + 's' });
        }
      }, 1000);
      this.setData({ authTimer: timer, isCountingDown: true });
    }
  },
  // 结束倒计时
  closeCountdonw () {
    if (this.data.authTimer && this.data.isCountingDown) {
      clearInterval(this.data.authTimer);
      this.setData({ isCountingDown: false, authCodeBtnText: '获取验证码' });
    }
  },
  // 手机号-图片验证码校验
  checkTelAndImgCode () {
    let ps_tel = false; let ps_imgCode = false;

    // 手机号校验
    ps_tel = (
      checkRequire(this.data.tel, '请输入手机号') &&
      checkMoblePhone(this.data.tel, '请输入正确的手机号码')
    );
    this.setData({ telPass: ps_tel });

    if (ps_tel) {
      // 图片验证码
      ps_imgCode = (
        checkRequire(this.data.imgCode, '请输入图片验证码') &&
        checkImgCode(this.data.imgCode, '请输入正确的图片验证码')
      );
      this.setData({ imgCodePass: ps_imgCode });
    }

    return ps_tel && ps_imgCode;
  },
  // 表单校验
  checkForm () {
    let ps_authCode = false;
    let ps_tel_imgcode = this.checkTelAndImgCode();
    if (ps_tel_imgcode) {
      ps_authCode = (
        checkRequire(this.data.authCode, '请输入短信验证码') &&
        checkAuthCode(this.data.authCode, '请输入正确的短信验证码')
      );
      this.setData({ authCodePass: ps_authCode });
    }
    return ps_authCode && ps_tel_imgcode;
  },

  /* --==================事件处理==================-- */
  // 表单提交
  handleSubmit (form) {
    if (this.checkForm()) {
      this.register();
    }
  },

  // 文本输入处理
  handleInput (e) {
    const param = {};
    param[e.currentTarget.dataset.type] = e.detail.value;
    this.setData(param);
  },

  // 获取验证码按钮点击处理
  async handleGetAuthCodeTap () {
    if (this.checkTelAndImgCode() && !this.data.isCountingDown) {
      this.getAuthCode();
    }
  },
  // 图片验证码点击处理
  handleImgCodeTap () {
    this.getImgCodeSrc();
  }
});